package com.czk;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/1/27 14:57
 */
public class FruitTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        // 拿到类名
        if (!Objects.equals(className, "com/czk/Fruit")) {
            return classfileBuffer;
        }
        String fileName = "F:\\IdeaProjects\\asm\\premain\\target\\classes\\com\\czk\\Fruit.class";
        return getClassBytes(fileName);

    }

    private byte[] getClassBytes(String fileName) {
        File file = new File(fileName);
        try (InputStream is = new FileInputStream(file);
             ByteArrayOutputStream bs = new ByteArrayOutputStream()) {
            long length = file.length();
            byte[] bytes = new byte[(int) length];
            int n;
            while ((n = is.read(bytes)) != -1) {
                bs.write(bytes, 0, n);
            }
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }
}
